﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace VisualSearch.Core
{
    class SearchDescriptionHandler : System.Web.IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            var openSearchDescription = new OpenSearchDescription
            {
                ShortName = "Visual Search",
                HtmlTemplateUrl =
                    new OpenSearchDescription.HtmlTemplate
                    {
                        TemplateUrl = String.Format("{0}{1}?q={{searchTerms}}", context.Request.Url.AbsoluteUri.Replace(context.Request.Url.AbsolutePath, string.Empty), System.Web.VirtualPathUtility.ToAbsolute("~/Search"))
                    },
                SuggestionTemplateUrl =
                    new OpenSearchDescription.SuggestionTemplate
                    {
                        TemplateUrl = String.Format("{0}{1}?q={{searchTerms}}", context.Request.Url.AbsoluteUri.Replace(context.Request.Url.AbsolutePath, string.Empty), System.Web.VirtualPathUtility.ToAbsolute("~/Suggestion"))
                    },
                SearchImage = new OpenSearchDescription.Image
                {
                    Width = 16,
                    Height = 16,
                    Url = String.Format("{0}{1}", context.Request.Url.AbsoluteUri.Replace(context.Request.Url.AbsolutePath, string.Empty), System.Web.VirtualPathUtility.ToAbsolute("~/favicon.ico"))
                }
            };
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(OpenSearchDescription));
            using (var memoryStream = new MemoryStream())
            {
                var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xmlSerializer.Serialize(xmlTextWriter, openSearchDescription);
                context.Response.ContentType = "application/xml";
                context.Response.Write(memoryStream.ToUTF8String());
                context.Response.Flush();
            }
        }

        #endregion
    }
}
